import sys
import os
import time
import pickle

import libtcodpy as libtcod

import console

class Bones(object):
    def __init__(self, player):
        score = 0
        for (song, level) in player.gigs:
            score += player.gigs[(song, level)] * level
        for item in player.inventory:
            score += item.value
        score += player.weapon.value + player.armor.value
        score += player.gold + player.fame

        if player.done == False:
            self.reason = 'Quit in a hurry'
        else:
            self.reason = player.done

        self.name = player.name
        self.score = score
        self.date = time.ctime()
        self.stamp = time.time()

    def __str__(self):
        return "%9d %s %s on %s" % (self.score, self.name, self.reason, self.date)

    def __cmp__(self, other):
        this = (self.score, self.stamp, self.name)
        that = (other.score, other.stamp, other.name)
        return cmp(that, this) #cmp(this, that)

def score(root, player):
    scores = load_scores()
    bones = Bones(player)
    scores.append(bones)
    scores.sort()

    save_scores(scores)

    root.background = libtcod.grey
    root.clear()
    root.foreground = libtcod.red
    root.print_center(root.width / 2, 2, libtcod.BKGND_SET, "RogueBand Hero: Hall of Fame")
    root.foreground = libtcod.white

    shown = False
    for ix, score in enumerate(scores[:10]):
        if score is bones:
            root.foreground = libtcod.yellow
            shown = True
        root.print_left(3, ix+4, libtcod.BKGND_SET, "%3d: %s" % (ix+1, score))
        root.foreground = libtcod.white
    if not shown:
        root.foreground = libtcod.yellow
        root.print_left(3, ix+5, libtcod.BKGND_SET, "%3d: %s" % (scores.index(bones)+1, bones))
        root.foreground = libtcod.white

    root.print_center(root.width / 2, root.height - 1, libtcod.BKGND_SET, "[Press Any Key to Quit]")
    root.flush()
    root.wait_for_keypress(True)

def load_scores(filename='bones.dat'):
    if not os.access(filename, os.R_OK):
        return []
    else:
        return pickle.load(open(filename, 'rb'))


def save_scores(scores, filename='bones.dat'):
    fp = open(filename, 'wb')
    pickle.dump(scores, fp, pickle.HIGHEST_PROTOCOL)
    fp.close()


